import store from "store/index";

//获得url链接中的参数
function getUrlKey(name) {
  return decodeURIComponent((new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(location.href) || [, ""])[1].replace(/\+/g, "%20")) || null;
}
//防抖函数
function debounce(func, delay) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
//获得焦点后选中
function focus(event) {
  event.currentTarget.select();
}
//将tree类型转换为list类型
//treeData是对象的数据   childObjName是子对象的属性名
export const getDataRowsByTree = (treeData) => {
  const rows = [];
  getDataRows(treeData, rows);
  return rows;
};
//递归的方法
const getDataRows = (data, rows) => {
  if (data.length > 0) {
    //找到所有的  children元素
    const childList = [];
    for (const item of data) {
      if (item.children && item.children.length > 0) {
        for (const child of item.children) {
          childList.push(child);
        }
      }
      item.children = [];
      rows.push(item);
    }
    getDataRows(childList, rows);
  } else {
    return;
  }
};

//刷新jwt的token刷新时间
function saveRefreshTime(param) {
  let nowTime = new Date();
  const tokenInfoModel = JSON.parse(window.sessionStorage.getItem("token"));
  if (!tokenInfoModel) return;
  let lastRefreshTime = tokenInfoModel.refreshTime ? new Date(tokenInfoModel.refreshTime) : new Date(-1);
  let expireTime = new Date(Date.parse(tokenInfoModel.expirationTime));

  let refreshCount = 30; //滑动系数,定义用户最大的停止活跃时间(分钟)
  if (lastRefreshTime >= nowTime) {
    lastRefreshTime = nowTime > expireTime ? nowTime : expireTime;
    lastRefreshTime.setMinutes(lastRefreshTime.getMinutes() + refreshCount);
    tokenInfoModel.refreshTime = lastRefreshTime;
  } else {
    tokenInfoModel.refreshTime = new Date(-1);
  }
  store.commit("user/setUserInformation", tokenInfoModel);
}
//关于localStorage的一些操作
export const localStorageUtils = {
  set(key, value) {
    if (!objIsNullOrWhiteSpace(key) && !objIsNullOrWhiteSpace(value)) {
      window.sessionStorage.setItem(key, value);
    }
  },
  get(key) {
    if (!objIsNullOrWhiteSpace(key)) {
      return window.sessionStorage.getItem(key);
    }
  },
  remove(key) {
    if (!objIsNullOrWhiteSpace(key)) {
      window.sessionStorage.removeItem(key);
    }
  },
  clear() {
    window.sessionStorage.clear();
  },
};
//判断一个变量有值且不为空
export const objIsNullOrWhiteSpace = (value) => {
  if (value != null && value != undefined && value.trim() != "") {
    return false;
  }
  return true;
};

export default { getUrlKey, debounce, focus, saveRefreshTime, localStorageUtils };
